<script setup>
import { inject, ref, watch } from "vue";
import { onShow, onReachBottom } from "@dcloudio/uni-app";
import { inventoryApi, totalApi } from "@/services/cloudlibrary";
import { productlst, cate } from "@/services/index";
import { operation } from "@/utils/num.js";
import { selectReplenishmentStore } from "@/stores/selectReplenishment";
import { formatPrice } from "@/utils/formatPrice";
const selectReplenishmentData = selectReplenishmentStore();

onShow(() => {
  getList();
  getTotal();
  numfun();
  num(selectChecked.value);
  cateFun();

  if (selectReplenishmentData.selectReplenishment.length > 0) {
    replenishmentData.value = selectReplenishmentData.selectReplenishment;
  } else {
    replenishmentData.value = [];
  }
});

// 库存统计
const total = ref(0);
const getTotal = async () => {
  try {
    // 发送请求
    let res = await totalApi();
    if (res.code === 200) {
      total.value = res.data.total;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

//下拉触底
onReachBottom(() => {
  // 触发下拉触底时执行的操作
  getList();
});

// 我的库存商品
const inventoryData = ref([]);
const form = ref({ page: 1, limit: 20 });
const status = ref("more");
const getList = async () => {
  form.value.keyword = keyword.value;
  form.value.cates = cates.value;
  try {
    status.value = "loading";
    // 发送请求
    let res = await productlst(form.value);
    if (res.code === 200) {
      if (selectChecked.value.length > 0) {
        selectChecked.value.forEach((element, index) => {
          res.data.list.forEach((element2, index2) => {
            if (element.product_id === element2.product_id) {
              element2["selectStatus"] = true;
              element2["product_num"] = element.product_num
                ? element.product_num
                : 0;
            }
          });
        });
      } else {
        res.data.list.map((item) => {
          item["selectStatus"] = false;
          item["product_num"] = 1;
        });
      }
      let arr = [];
      arr = res.data.list;
      inventoryData.value = inventoryData.value.concat(arr);

      // 判断是否有选好的商品
      if (selectReplenishmentData.selectReplenishment.length > 0) {
        replenishmentData.value = selectReplenishmentData.selectReplenishment;
        replenishmentData.value.forEach((item1, index1) => {
          inventoryData.value.forEach((item2, index2) => {
            if (item1.product_id == item2.product_id) {
              item2["product_num"] = item1.product_num;
              item2["selectStatus"] = true;
            }
          });
        });
        selectData.value = replenishmentData.value;
        selectChecked.value = selectData.value;
        selectCount.value = selectChecked.value.length;
      } else {
        replenishmentData.value = [];
        selectData.value = [];
        selectChecked.value = [];
        inventoryData.value.forEach((item3, index3) => {
          item3["product_num"] = 1;
          item3["selectStatus"] = false;
        });
      }

      if (res.data.list.length < form.value.limit) {
        status.value = "no-more";
      } else {
        status.value = "more";
      }
      form.value.page++;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }

  numfun();
  num(selectChecked.value);
};

const keyword = ref("");
const aloneChecked = ref(false);
const checkboxValue1 = ref([]);
const selectChecked = ref([]);
const selectData = ref([]);
const replenishmentData = ref([]);
const selectCount = ref(0);
const show = ref(false);
const priceCount = ref(0);

// 搜索
const searchfun = () => {
  form.value.keyword = keyword.value;
  inventoryData.value = [];
  form.value.page = 1;
  getList();
};
function num(arr) {
  setTimeout(() => {
    let num = 0;
    arr.forEach((element, index) => {
      if (element.selectStatus) {
        num = operation(
          num,
          operation(element.vip_price, element.product_num, 2, "multiply"),
          2,
          "add"
        );
      }
    });
    priceCount.value = num;
  }, 100);
}

// 加号
const showNumberBox = (index) => {
  let isnew = true;
  inventoryData.value[index].selectStatus = true;
  if (selectData.value.length <= 0) {
    selectData.value.push(inventoryData.value[index]);
  } else {
    inventoryData.value.forEach((element2, index2) => {
      if (index2 == index) {
        selectData.value.forEach((element, index1) => {
          if (element.product_id == element2.product_id) {
            isnew = false;
            element["selectStatus"] = true;
            element["product_num"] = element.product_num
              ? element.product_num
              : 0;
            element2.product_num = element.product_num
              ? element.product_num
              : 0;
          } else {
          }
        });

        if (isnew) {
          inventoryData.value[index2].product_num = 1;
          selectData.value.push(inventoryData.value[index2]);
        }
      }
    });
  }

  selectChecked.value = selectData.value;
  selectCount.value = selectChecked.value.length;
  num(selectChecked.value);
};

// 步进器，数量
const valChange1 = (e, index) => {
  inventoryData.value.forEach((item1, index1) => {
    if (index1 == index) {
      selectData.value.forEach((item2, index2) => {
        if (item1.selectStatus == true) {
          if (item1.product_id == item2.product_id) {
            item1.product_num = e.value;
            item2.product_num = e.value;
            // item1.product_num = e.value?e.value:0;
            // item2.product_num = e.value?e.value:0;
          }
        }
      });
    }
  });

  // inventoryData.value[index].product_num = e.value;
  num(selectChecked.value);
};
// 步进器，数量
const valChange2 = (e, index) => {
  selectData.value.forEach((item4, index4) => {
    if (index4 == index) {
      inventoryData.value.forEach((item3, index3) => {
        if (item3.selectStatus == true) {
          if (item3.product_id == item4.product_id) {
            item3.product_num = e.value;
            item4.product_num = e.value;
          }
        }
      });
    }
  });
  // inventoryData.value[index].product_num = e.value;
  num(selectChecked.value);
};
// 查看明细
const showDeatil = () => {
  show.value = !show.value;
  if (
    selectChecked.value.length === selectCount.value &&
    selectCount.value > 0
  ) {
    aloneChecked.value = true;
  } else {
    aloneChecked.value = false;
  }
  num(selectChecked.value);
};

// 全选
const changeAll = () => {
  aloneChecked.value = !aloneChecked.value;
  selectChecked.value.forEach((item, index) => {
    if (aloneChecked.value) {
      item.selectStatus = true;
      selectCount.value = selectData.value.length;
    } else {
      item.selectStatus = false;
      selectCount.value = 0;
    }
  });
  num(selectChecked.value);
};
// 复选框
const checkboxChange = (e, index) => {
  aloneChecked.value = false;
  selectChecked.value[index].selectStatus = !selectChecked.value[index]
    .selectStatus;
  if (selectChecked.value[index].selectStatus) {
    selectCount.value += 1;
  } else {
    selectCount.value -= 1;
  }

  if (selectChecked.value.length === selectCount.value) {
    aloneChecked.value = true;
  } else {
    aloneChecked.value = false;
  }
  num(selectChecked.value);
};

// 选好
const goorderfun = () => {
  if (numfun() <= 0) {
    uni.showToast({
      title: "商品数量不能为0,请选择",
      icon: "none",
    });
    return;
  }
  selectChecked.value = selectData.value;
  replenishmentData.value = [];
  selectChecked.value.forEach((item, index) => {
    if (item.product_num > 0 && item.vip_price > 0) {
      if (!replenishmentData.value.includes[index] && item.selectStatus) {
        replenishmentData.value.push(item);
      }
    }
  });
  replenishmentData.value.total_price = priceCount.value;
  selectReplenishmentData.setselectReplenishment(replenishmentData.value);
  if (replenishmentData.value.length > 0) {
    uni.navigateTo({
      url: "/pages/cloudlibrary/replenishment_confirm/index",
    });
  } else {
    uni.showToast({
      title: "价格不能为0，请选择商品",
      icon: "none",
    });
  }
  num(selectChecked.value);
};

//计算商品总数
function numfun() {
  let num = 0;
  if (selectData.value.length > 0) {
    selectData.value.forEach((element, index) => {
      if (element.selectStatus) {
        num += element.product_num;
      }
    });
    return num;
  } else {
    return num;
  }
}

const close = () => {
  show.value = false;
  showPopup.value = false;
  pay_pass.value = "";
};

// 分类查询
const cateData = ref([]);
const cateFun = async () => {
  try {
    // 发送请求
    let res = await cate();
    cateData.value = res.data;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    cateData.value = "";
  }
};

const cates = ref("");
const showPopup = ref(false);
const type_classIndex = ref("");
const closepopup = () => {
  showPopup.value = false;
  cates.value = "";
  type_classIndex.value = "";
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getList();
};
// 筛选确认
const popupSubmit = () => {
  showPopup.value = false;
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getList();
};
const selectClassType = (index) => {
  inventoryData.value = [];
  form.value.page = 1;
  type_classIndex.value = index;
  cates.value = index;
  getList();
};
</script>

<template>
  <view class="content">
    <view class="content-top">
      <up-search
        placeholder="商品名称"
        :showAction="false"
        v-model="keyword"
        @search="searchfun"
      ></up-search>
      <view class="search" @click="showPopup = true">
        <image
          src="@/pages/cloudlibrary/static/search.png"
          mode="scaleToFill"
        />
      </view>
    </view>
    <view class="info-circle-ts">
      <up-icon name="info-circle" color="#DB8900" size="32rpx"></up-icon>
      <text>商品补货，仅支持采购到云仓库存，如需发货，请到首页下单</text>
    </view>
    <view
      class="content-list"
      v-show="inventoryData && inventoryData.length > 0"
    >
      <view
        class="content-list-item"
        v-for="(item, index) in inventoryData"
        :key="index"
      >
        <view class="content-list-item-left">
          <image :src="item.image" mode="aspectFill" />
          <view class="content-list-item-dec">
            <view class="content-list-item-name">{{ item.store_name }}</view>
            <view class="goods-dec">默认</view>

            <view class="content-list-item-price"
              >￥{{ formatPrice(item.vip_price) }}</view
            >
          </view>
        </view>

        <view class="select-shop">
          <up-number-box
            :min="0"
            v-model="item.product_num"
            :show="item.selectStatus"
            v-if="item.selectStatus"
            @change="
              (e) => {
                valChange1(e, index);
              }
            "
            bgColor="#ffffff"
          ></up-number-box>
          <view class="select-shop-add" v-if="!item.selectStatus">
            <up-icon
              name="plus"
              color="#262626"
              size="30rpx"
              @click="showNumberBox(index)"
            ></up-icon>
          </view>
        </view>
      </view>
    </view>
    <view class="nodate-bt" v-if="inventoryData.length === 0">
      <image src="/static/nodate/nodate.png" mode="widthFix"></image>
    </view>

    <uni-load-more color="#c6c5c3" :status="status" />
  </view>

  <view class="foodr-bt">
    <view class="foodr-bt-left">
      <up-checkbox
        :customStyle="{ marginBottom: '8px' }"
        label="全选"
        name="agree"
        usedAlone
        shape="circle"
        size="48rpx"
        activeColor="#F3498B "
        v-model:checked="aloneChecked"
        @change="changeAll"
        v-if="show"
      >
      </up-checkbox>
    </view>
    <view class="foodr-bt-right">
      <view class="foodr-bt-right-text">
        <view class="bt-money"
          >合计：<text class="money-icon">￥</text
          ><text>{{ formatPrice(priceCount || 0) }}</text></view
        >
        <view class="bt-text"
          >已选{{ numfun() }}件<text @click="showDeatil">查看明细</text
          ><up-icon
            :name="true ? 'arrow-up' : 'arrow-down'"
            color="#F3498B "
            size="38rpx"
          ></up-icon>
        </view>
      </view>
      <view class="bt-sbuit" @click="goorderfun()">去支付</view></view
    >
  </view>

  <up-popup
    :show="show"
    mode="bottom"
    @close="close"
    @open="open"
    :closeable="true"
    round="20"
  >
    <view class="content-list-title">已选商品</view>
    <view class="content-list content-list-view">
      <scroll-view
        :scroll-top="scrollTop"
        scroll-y="true"
        class="scroll-Y"
        :show-scrollbar="false"
        @scrolltoupper="upper"
        @scrolltolower="lower"
        @scroll="scroll"
      >
        <up-checkbox-group v-model="checkboxValue1" placement="column">
          <view
            class="content-select-item"
            v-for="(item, index) in selectData"
            :key="index"
          >
            <up-checkbox
              :customStyle="{ marginBottom: '8px' }"
              shape="circle"
              activeColor="#F3498B "
              size="48rpx"
              @change="
                (e) => {
                  checkboxChange(e, index);
                }
              "
              :name="item.product_id"
              :key="item.product_id"
              :checked="item.selectStatus"
            >
            </up-checkbox>
            <view class="content-list-item select-content-list-item">
              <view class="content-list-item-left">
                <image :src="item.image" mode="aspectFill" />
                <view class="content-list-item-dec">
                  <view class="content-list-item-name">{{
                    item.store_name
                  }}</view>
                  <view class="goods-dec">默认</view>

                  <view class="content-list-item-price"
                    >￥{{ formatPrice(item.vip_price) }}</view
                  >
                </view>
              </view>

              <!-- <view class="content-list-item-right">
                余{{ item.quantity }}
              </view> -->

              <view class="select-shop select-shop-k">
                <up-number-box
                  bgColor="#ffffff"
                  v-model="item.product_num"
                  :min="0"
                  @change="
                    (e) => {
                      valChange2(e, index);
                    }
                  "
                ></up-number-box>
              </view>
            </view>
          </view>
        </up-checkbox-group>
      </scroll-view>
    </view>
  </up-popup>

  <!-- 筛选 -->
  <u-popup
    :show="showPopup"
    mode="bottom"
    round="10"
    @close="close"
    @open="open"
    closeable
    class="showPopup"
  >
    <view class="popup-content">
      <view class="popup-content-title">筛选</view>
      <u-line></u-line>
      <view class="popup-content-dec">
        <view class="popup-content-card">
          <text>分类</text>
          <view class="popup-content-card-btn">
            <view v-for="(item, index) in cateData" :key="index">
              <u-button
                class="popup-button"
                @click="selectClassType(item.id)"
                :class="
                  type_classIndex === item.id ? 'popup-button-active' : ''
                "
              >
                {{ item.name }}
              </u-button>
            </view>
          </view>
        </view>
      </view>

      <view class="popup-content-box">
        <view class="popup-content-bt">
          <u-button
            class="popup-content-qx"
            text="取消"
            @click="closepopup"
          ></u-button>
          <u-button
            class="popup-content-cl"
            text="筛选"
            @click="popupSubmit"
          ></u-button>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
